{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "0813更新：\n",
    "\n",
    "combine-model： 把词向量和字向量信息全部丢进来训练。\n",
    "\n",
    "一共有4路输入，wd 和 ch 各两路。\n",
    "\n",
    "title 部分使用 bigru, content 部分使用 han-bigru.\n",
    "\n",
    "对 title 和 content 的输出，拼起来，得到维度为 hidden_size × 2 × 4\n",
    "\n",
    "在后边的 fc 中加上 dropout 0.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting ...\n",
      "removed the existing summary files.\n",
      "Prepared, costed time 0.502059 s.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt \n",
    "import pickle\n",
    "import os\n",
    "import sys\n",
    "import shutil\n",
    "import tqdm\n",
    "import time\n",
    "\n",
    "\n",
    "time0 = time.time()\n",
    "print('Starting ...')\n",
    "model_name = 'c2-1-bigru-256'                    # 模型名称\n",
    "wd_embedding = np.load('../data/W_embedding.npy').astype(np.float32)                      # 导入预训练好的词向量\n",
    "ch_embedding = np.load('../data/ch_W_embedding.npy').astype(np.float32)  # 字向量\n",
    "model_path = '../ckpt/' + model_name + '/'                  # 模型保存位置\n",
    "summary_path = '../summary/' + model_name + '/'             # summary 位置\n",
    "result_path = '../result/' + model_name + '.csv'            # result.csv 位置\n",
    "scores_path = '../scores/' + model_name + '.npy'            # scores.npy 位置\n",
    "local_scores_path = '../local_scores/' + model_name + '.npy'\n",
    "\n",
    "\n",
    "if not os.path.exists(model_path):\n",
    "    os.makedirs(model_path)         \n",
    "model_path = model_path + 'model.ckpt'\n",
    "if os.path.exists(summary_path):   # 删除原来的 summary 文件，避免重合\n",
    "    print('removed the existing summary files.')\n",
    "    shutil.rmtree(summary_path)\n",
    "os.makedirs(summary_path)          # 然后再次创建\n",
    "    \n",
    "# ##################### config ######################\n",
    "n_step1 = wd_sent_len = 30                   # title句子长度\n",
    "n_step2 = wd_doc_len = 10                # content 长度\n",
    "n_step3 = ch_sent_len = 52\n",
    "n_step4 = ch_doc_len = 10\n",
    "input_size = embedding_size = 256       # 字向量长度\n",
    "n_class = 1999                          # 类别总数\n",
    "hidden_size = 256    # 隐含层节点数\n",
    "fc_hidden_size = 1024                   # fc 层节点数\n",
    "title_attention_size = sent_attention_size = doc_attention_size = hidden_size * 2\n",
    "n_layer = 1        # bi-gru 层数\n",
    "max_grad_norm = 1.0  # 最大梯度（超过此值的梯度将被裁剪）\n",
    "global_step = 0\n",
    "print('Prepared, costed time %g s.' % (time.time() - time0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Building model ...\n",
      "Finished creating the bigru model.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "config = tf.ConfigProto()\n",
    "config.gpu_options.allow_growth = True\n",
    "sess = tf.Session(config=config)\n",
    "from tensorflow.contrib import rnn\n",
    "import tensorflow.contrib.layers as layers\n",
    "\n",
    "'''\n",
    "双端 GRU，知乎问题多标签分类。\n",
    "'''\n",
    "print('Building model ...')\n",
    "keep_prob = tf.placeholder(tf.float32, [])\n",
    "lr = tf.placeholder(tf.float32)\n",
    "batch_size = tf.placeholder(tf.int32, [])  # 注意类型必须为 tf.int32\n",
    "tst = tf.placeholder(tf.bool)\n",
    "n_updates = tf.placeholder(tf.int32)      # training iteration,传入 bn 层\n",
    "update_emas = list()                       # BN 层中所有的更新操作\n",
    "\n",
    "\n",
    "def weight_variable(shape, name):\n",
    "    \"\"\"Create a weight variable with appropriate initialization.\"\"\"\n",
    "    initial = tf.truncated_normal(shape, stddev=0.1)\n",
    "    return tf.Variable(initial, name=name)\n",
    "\n",
    "def bias_variable(shape, name):\n",
    "    \"\"\"Create a bias variable with appropriate initialization.\"\"\"\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.Variable(initial, name=name)\n",
    "\n",
    "def batchnorm(Ylogits, is_test, num_updates, offset, convolutional=False):\n",
    "    \"\"\"batchnormalization.\n",
    "    Args:\n",
    "        Ylogits: 1D向量或者是3D的卷积结果。\n",
    "        num_updates: 迭代的global_step\n",
    "        offset：表示beta，全局均值；在 RELU 激活中一般初始化为 0.1。\n",
    "        scale：表示lambda，全局方差；在 sigmoid 激活中需要，这 RELU 激活中作用不大。\n",
    "        m: 表示batch均值；v:表示batch方差。\n",
    "        bnepsilon：一个很小的浮点数，防止除以 0.\n",
    "    Returns:\n",
    "        Ybn: 和 Ylogits 的维度一样，就是经过 Batch Normalization 处理的结果。\n",
    "        update_moving_everages：更新mean和variance，主要是给最后的 test 使用。\n",
    "    \"\"\"\n",
    "    exp_moving_avg = tf.train.ExponentialMovingAverage(0.999, num_updates) # adding the iteration prevents from averaging across non-existing iterations\n",
    "    bnepsilon = 1e-5\n",
    "    if convolutional:\n",
    "        mean, variance = tf.nn.moments(Ylogits, [0, 1, 2])\n",
    "    else:\n",
    "        mean, variance = tf.nn.moments(Ylogits, [0])\n",
    "    update_moving_everages = exp_moving_avg.apply([mean, variance])\n",
    "    m = tf.cond(is_test, lambda: exp_moving_avg.average(mean), lambda: mean)\n",
    "    v = tf.cond(is_test, lambda: exp_moving_avg.average(variance), lambda: variance)\n",
    "    Ybn = tf.nn.batch_normalization(Ylogits, m, v, offset, None, bnepsilon)\n",
    "    return Ybn, update_moving_everages\n",
    "\n",
    "def gru_cell():\n",
    "    with tf.variable_scope('gru_cell'):\n",
    "        cell = rnn.GRUCell(hidden_size, reuse=tf.get_variable_scope().reuse)\n",
    "    return rnn.DropoutWrapper(cell, output_keep_prob=keep_prob)\n",
    "  \n",
    "def bi_gru(inputs, seg_num=batch_size):\n",
    "    \"\"\"build the bi-GRU network. Return the encoder represented vector.\n",
    "    n_step: 句子的词数量；或者文档的句子数。\n",
    "    seg_num: 序列的数量，原本应该为 batch_size, 但是这里将 batch_size 个 doc展开成很多个句子。\n",
    "    \"\"\"\n",
    "    cells_fw = [gru_cell() for _ in range(n_layer)]\n",
    "    cells_bw = [gru_cell() for _ in range(n_layer)]\n",
    "    initial_states_fw = [cell_fw.zero_state(seg_num, tf.float32) for cell_fw in cells_fw]\n",
    "    initial_states_bw = [cell_bw.zero_state(seg_num, tf.float32) for cell_bw in cells_bw] \n",
    "    outputs, _, _ = rnn.stack_bidirectional_dynamic_rnn(cells_fw, cells_bw, inputs, \n",
    "                        initial_states_fw = initial_states_fw, initial_states_bw = initial_states_bw, dtype=tf.float32)\n",
    "    # outputs: Output Tensor shaped: seg_num, max_time, layers_output]，其中layers_output=hidden_size * 2 在这里。\n",
    "    return outputs\n",
    "   \n",
    "def task_specific_attention(inputs, output_size,\n",
    "                            initializer=layers.xavier_initializer(),\n",
    "                            activation_fn=tf.tanh, scope=None):\n",
    "    \"\"\"\n",
    "    Performs task-specific attention reduction, using learned\n",
    "    attention context vector (constant within task of interest).\n",
    "    Args:\n",
    "        inputs: Tensor of shape [batch_size, units, input_size]\n",
    "            `input_size` must be static (known)\n",
    "            `units` axis will be attended over (reduced from output)\n",
    "            `batch_size` will be preserved\n",
    "        output_size: Size of output's inner (feature) dimension\n",
    "    Returns:\n",
    "        outputs: Tensor of shape [batch_size, output_dim].\n",
    "    \"\"\"\n",
    "    assert len(inputs.get_shape()) == 3 and inputs.get_shape()[-1].value is not None\n",
    "    with tf.variable_scope(scope or 'attention') as scope:\n",
    "        # u_w, attention 向量\n",
    "        attention_context_vector = tf.get_variable(name='attention_context_vector',\n",
    "                                                   shape=[output_size],\n",
    "                                                   initializer=initializer,\n",
    "                                                   dtype=tf.float32)\n",
    "        # 全连接层，把 h_i 转为 u_i ， shape= [batch_size, units, input_size] -> [batch_size, units, output_size]\n",
    "        input_projection = layers.fully_connected(inputs, output_size,\n",
    "                                                  activation_fn=activation_fn,\n",
    "                                                  scope=scope)\n",
    "        # 输出 [batch_size, units]\n",
    "        vector_attn = tf.reduce_sum(tf.multiply(input_projection, attention_context_vector), axis=2, keep_dims=True)\n",
    "        attention_weights = tf.nn.softmax(vector_attn, dim=1)   \n",
    "        tf.summary.histogram('attention_weigths', attention_weights)\n",
    "        weighted_projection = tf.multiply(inputs, attention_weights)   # ???源代码,原文应该是对 hi 加权！！\n",
    "        outputs = tf.reduce_sum(weighted_projection, axis=1)\n",
    "        return outputs  # 输出 [batch_size, units]\n",
    "\n",
    "def bigru_reference(inputs):\n",
    "    \"\"\"双端 gru 模型。title部分。\n",
    "    Args: \n",
    "        X_inputs: tensor.shape=(batch_size, title_len)\n",
    "    Returns:\n",
    "        title_outputs: tensor.shape=(batch_size, hidden_size(*2 for bigru))\n",
    "    \"\"\"\n",
    "    with tf.variable_scope('title_encoder'):  # 生成 title 的向量表示\n",
    "        title_outputs = bi_gru(inputs)\n",
    "        title_attn_outputs = task_specific_attention(title_outputs, title_attention_size)   \n",
    "    return title_attn_outputs   # shape = [batch_size, hidden_size*2]\n",
    "\n",
    "\n",
    "def han_reference(inputs, sent_len, doc_len=10):\n",
    "    \"\"\"分层 attention 模型。content部分。\n",
    "    Args: \n",
    "        X_inputs: tensor.shape=(batch_size, doc_len*sent_len)\n",
    "    Returns:\n",
    "        doc_attn_outputs: tensor.shape=(batch_size, hidden_size(*2 for bigru))\n",
    "    \"\"\"\n",
    "    sent_inputs = tf.reshape(inputs,[batch_size*doc_len, sent_len, embedding_size]) # shape=(?, 40, 256)\n",
    "    with tf.variable_scope('sentence_encoder'):  # 生成句向量\n",
    "        sent_outputs = bi_gru(sent_inputs, seg_num=batch_size*doc_len)\n",
    "        sent_attn_outputs = task_specific_attention(sent_outputs, sent_attention_size) # [batch_size*doc_len, hidden_size*2]\n",
    "        with tf.variable_scope('dropout'):\n",
    "            sent_attn_outputs = tf.nn.dropout(sent_attn_outputs, keep_prob)\n",
    "    with tf.variable_scope('doc_encoder'):  # 生成句向量\n",
    "        doc_inputs = tf.reshape(sent_attn_outputs, [batch_size, doc_len, hidden_size*2])\n",
    "        doc_outputs = bi_gru(doc_inputs)  # [batch_size, doc_len, hidden_size*2]\n",
    "        doc_attn_outputs = task_specific_attention(doc_outputs, doc_attention_size) # [batch_size, hidden_size*2]\n",
    "    return doc_attn_outputs    # [batch_size, hidden_size*2]\n",
    "\n",
    "    \n",
    "with tf.device('/gpu:0'):\n",
    "    with tf.variable_scope('embedding') as vs:\n",
    "        word_embedding = tf.get_variable(name=\"word_embedding\", shape=wd_embedding.shape, \n",
    "                            initializer=tf.constant_initializer(wd_embedding), trainable=True)   # fine-tune\n",
    "        char_embedding = tf.get_variable(name=\"char_embedding\", shape=ch_embedding.shape, \n",
    "                            initializer=tf.constant_initializer(ch_embedding), trainable=True)   # fine-tune\n",
    "        \n",
    "with tf.name_scope('Inputs'):\n",
    "    X1_inputs = tf.placeholder(tf.int64, [None, wd_sent_len], name='X1_input')  # wd_title\n",
    "    X2_inputs = tf.placeholder(tf.int64, [None, wd_doc_len*wd_sent_len], name='X2_input')  # wd_content\n",
    "    X3_inputs = tf.placeholder(tf.int64, [None, ch_sent_len], name='X3_input')  # ch_title\n",
    "    X4_inputs = tf.placeholder(tf.int64, [None, ch_doc_len*ch_sent_len], name='X4_input')  # ch_content\n",
    "    y_inputs = tf.placeholder(tf.float32, [None, n_class], name='y_input')    \n",
    "    inputs1 = tf.nn.embedding_lookup(word_embedding, X1_inputs)\n",
    "    inputs2 = tf.nn.embedding_lookup(word_embedding, X2_inputs)\n",
    "    inputs3 = tf.nn.embedding_lookup(char_embedding, X3_inputs)\n",
    "    inputs4 = tf.nn.embedding_lookup(char_embedding, X4_inputs)\n",
    "\n",
    "with tf.variable_scope('wd-encoder'):    \n",
    "    with tf.variable_scope('wd-title'):\n",
    "        wd_output_title = bigru_reference(inputs1)                            # [batch_size, hidden_size*2]\n",
    "    with tf.variable_scope('wd-content'):\n",
    "        wd_output_content = han_reference(inputs2, sent_len=wd_sent_len)      # [batch_size, hidden_size*2]\n",
    "    \n",
    "with tf.variable_scope('ch-encoder'):\n",
    "    with tf.variable_scope('ch-title'):\n",
    "        ch_output_title = bigru_reference(inputs3)\n",
    "    with tf.variable_scope('ch-content'):\n",
    "        ch_output_content = han_reference(inputs4, sent_len=ch_sent_len)      # [batch_size, hidden_size*2]\n",
    "\n",
    "    \n",
    "with tf.variable_scope('fc-bn-layer'):\n",
    "    output = tf.concat([wd_output_title, wd_output_content, ch_output_title, ch_output_content], axis=1)  # shape=[batch_size, n_filter_total*2]\n",
    "    W_fc = weight_variable([hidden_size*8, fc_hidden_size], name='Weight_fc')\n",
    "    tf.summary.histogram('W_fc', W_fc)\n",
    "    h_fc = tf.matmul(output, W_fc, name='h_fc')\n",
    "    beta_fc = bias_variable([fc_hidden_size], name=\"beta_fc\")\n",
    "    tf.summary.histogram('beta_fc', beta_fc)\n",
    "    fc_bn, update_ema_fc = batchnorm(h_fc, tst, n_updates, beta_fc, convolutional=False)\n",
    "    update_emas.append(update_ema_fc)\n",
    "    fc_bn_relu = tf.nn.relu(fc_bn, name=\"relu\")\n",
    "    fc_bn_drop = tf.nn.dropout(fc_bn_relu, keep_prob, name=\"fc_dropout\")\n",
    "\n",
    "with tf.variable_scope('out_layer'):\n",
    "    W_out = weight_variable(shape=[fc_hidden_size, n_class], name='Weight_out')\n",
    "    tf.summary.histogram('Weight_out', W_out)\n",
    "    b_out = bias_variable([n_class], name='bias_out') \n",
    "    tf.summary.histogram('bias_out', b_out)\n",
    "    y_pred = tf.nn.xw_plus_b(fc_bn_drop, W_out, b_out, name='y_pred')  #每个类别的分数 scores\n",
    "    \n",
    "with tf.name_scope('cost'):\n",
    "    cost = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=y_pred, labels=y_inputs))\n",
    "    tf.summary.scalar('cost', cost)\n",
    "\n",
    "#  ------------- 优化器设置 ---------------------\n",
    "with tf.name_scope('AdamOptimizer1'):\n",
    "    tvars1 = tf.trainable_variables()\n",
    "    grads1, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars1), max_grad_norm)\n",
    "    optimizer1 = tf.train.AdamOptimizer(learning_rate=lr)\n",
    "    train_op1 = optimizer1.apply_gradients(zip(grads1, tvars1),\n",
    "        global_step=tf.contrib.framework.get_or_create_global_step())\n",
    "    \n",
    "with tf.name_scope('AdamOptimizer2'):\n",
    "    tvars2 = [tvar for tvar in tvars1 if 'embedding' not in tvar.name]\n",
    "    grads2, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars2), max_grad_norm)\n",
    "    optimizer2 = tf.train.AdamOptimizer(learning_rate=lr)\n",
    "    train_op2 = optimizer2.apply_gradients(zip(grads2, tvars2),\n",
    "        global_step=tf.contrib.framework.get_or_create_global_step())\n",
    "update_op = tf.group(*update_emas)   # 更新 BN 参数\n",
    "\n",
    "\n",
    "# summary\n",
    "merged = tf.summary.merge_all() # summary\n",
    "train_writer = tf.summary.FileWriter(summary_path + 'train', sess.graph)\n",
    "test_writer = tf.summary.FileWriter(summary_path + 'test')\n",
    "print 'Finished creating the bigru model.'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "n_tr_batch=22656\n",
      "n_va_batches=782\n",
      "Every thing prepared!\n"
     ]
    }
   ],
   "source": [
    "sys.path.append('..')\n",
    "from data_helpers import BatchGenerator\n",
    "from data_helpers import to_categorical\n",
    "from evaluator import score_eval\n",
    "\n",
    "\n",
    "wd_train_path = '/home/peng/huangyongye/wd-data/seg_train/'\n",
    "wd_valid_path = '/home/peng/huangyongye/wd-data/seg_valid/'\n",
    "ch_train_path = '/home/peng/huangyongye/ch-data/seg_train/'\n",
    "ch_valid_path = '/home/peng/huangyongye/ch-data/seg_valid/'\n",
    "\n",
    "\n",
    "tr_batches = os.listdir(wd_train_path)   # batch 文件名列表\n",
    "va_batches = os.listdir(wd_valid_path)\n",
    "n_tr_batches = len(tr_batches)\n",
    "n_va_batches = len(va_batches)\n",
    "\n",
    "# 测试用\n",
    "# n_tr_batches = 500  \n",
    "# n_va_batches = 50\n",
    "print('n_tr_batch=%d' % n_tr_batches)\n",
    "print('n_va_batches=%d' % n_va_batches)\n",
    "\n",
    "\n",
    "def get_batch(batch_id, mode='train'):\n",
    "    \"\"\"get a batch from data_path.\n",
    "    model: 'train', 'valid' 三种方式。\n",
    "    \"\"\"\n",
    "    if mode == 'train':\n",
    "        wd_path = wd_train_path\n",
    "        ch_path = ch_train_path \n",
    "    if mode == 'valid':\n",
    "        wd_path = wd_valid_path\n",
    "        ch_path = ch_valid_path\n",
    "    wd_batch = np.load(wd_path + str(batch_id) + '.npz')\n",
    "    wd_X_batch = wd_batch['X']\n",
    "    X1_batch = wd_X_batch[:, :n_step1]\n",
    "    X2_batch = wd_X_batch[:, n_step1:]\n",
    "    ch_batch = np.load(ch_path + str(batch_id) + '.npz')\n",
    "    ch_X_batch = ch_batch['X']\n",
    "    X3_batch = ch_X_batch[:, :n_step3]\n",
    "    X4_batch = ch_X_batch[:, n_step3:]\n",
    "    y_batch = ch_batch['y']\n",
    "    return [X1_batch, X2_batch, X3_batch, X4_batch, y_batch]\n",
    "\n",
    "\n",
    "def valid_epoch():\n",
    "    \"\"\"Test on the valid data.\"\"\"\n",
    "    _costs = 0.0\n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    marked_labels_list = list()   # 真实标签\n",
    "    for i in xrange(n_va_batches):\n",
    "        [X1_batch, X2_batch, X3_batch, X4_batch, y_batch] = get_batch(i, mode='valid')\n",
    "        marked_labels_list.extend(y_batch)\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        fetches = [merged, cost, y_pred]  \n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, X3_inputs:X3_batch, X4_inputs:X4_batch, y_inputs:y_batch, \n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "        summary, _cost, predict_labels = sess.run(fetches, feed_dict)\n",
    "        _costs += _cost\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "    precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "    mean_cost = _costs / n_va_batches\n",
    "    return mean_cost, precision, recall, f1\n",
    "\n",
    "print('Every thing prepared!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  模型训练"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之前的训练速度 9334.15 s/epoch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tr_batch_num=22656\n",
      "OK!\n"
     ]
    }
   ],
   "source": [
    "_lr = 1.5e-3\n",
    "decay = 0.85 \n",
    "# 正式\n",
    "max_epoch = 3            # 超多 max_epoch 以后开始降低 lr\n",
    "max_max_epoch = 9       # 最多迭代的次数\n",
    "valid_step = 8000        # 每 valid_step 就进行一次 valid 运算\n",
    "decay_step = 11000\n",
    "\n",
    "# 测试\n",
    "# max_epoch = 1            # 超多 max_epoch 以后开始降低 lr\n",
    "# max_max_epoch = 3       # 最多迭代的次数\n",
    "# decay_step = 500\n",
    "# valid_step = 250\n",
    "\n",
    "print('tr_batch_num=%d' % n_tr_batches)\n",
    "saver = tf.train.Saver(max_to_keep=3)           # 最多保存的模型数量\n",
    "sess.run(tf.global_variables_initializer())\n",
    "last_f1 = 0.40\n",
    "model_num = 0\n",
    "global_step = 0\n",
    "print('OK!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EPOCH 1, lr= 0.0015\n",
      "Global_step=8000: valid cost=0.00464288; p=1.19449, r=0.491513, f1=0.348225, time=4256.25s\n",
      "Global_step=16000: valid cost=0.00432813; p=1.26633, r=0.51939, f1=0.368321, time=4257.86s\n",
      "EPOCH 2, lr= 0.00108375\n",
      "Global_step=24000: valid cost=0.00422078; p=1.29733, r=0.530832, f1=0.376698, time=4256.84s\n",
      "Global_step=32000: valid cost=0.00420759; p=1.31526, r=0.537754, f1=0.381695, time=4271.25s\n",
      "Global_step=40000: valid cost=0.00415157; p=1.32378, r=0.540952, f1=0.384023, time=4279.22s\n",
      "EPOCH 3, lr= 0.000783009\n",
      "Global_step=48000: valid cost=0.00410971; p=1.33327, r=0.545172, f1=0.386949, time=4273.63s\n",
      "Global_step=56000: valid cost=0.00407327; p=1.34816, r=0.550414, f1=0.390844, time=4270.97s\n",
      "Global_step=64000: valid cost=0.00405052; p=1.35365, r=0.552047, f1=0.392129, time=4267.94s\n",
      "('the save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-1')\n",
      "Begin updating embedding.\n",
      "EPOCH 4, lr= 0.000565724\n",
      "Global_step=72000: valid cost=0.0040885; p=1.35742, r=0.553244, f1=0.39305, time=4507.81s\n",
      "Global_step=80000: valid cost=0.00402771; p=1.36901, r=0.558281, f1=0.396563, time=4672.46s\n",
      "Global_step=88000: valid cost=0.00399291; p=1.37956, r=0.562403, f1=0.399528, time=4662.72s\n",
      "EPOCH 5, lr= 0.000408736\n",
      "Global_step=96000: valid cost=0.00397754; p=1.38567, r=0.564865, f1=0.401283, time=4659.79s\n",
      "('The save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-2')\n",
      "Global_step=104000: valid cost=0.00396867; p=1.38928, r=0.56614, f1=0.402229, time=4644.64s\n",
      "('The save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-3')\n",
      "Global_step=112000: valid cost=0.00395209; p=1.39424, r=0.567888, f1=0.403528, time=4599.36s\n",
      "('The save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-4')\n",
      "EPOCH 6, lr= 0.000295312\n",
      "Global_step=120000: valid cost=0.00395723; p=1.39471, r=0.568042, f1=0.403645, time=4597.65s\n",
      "('The save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-5')\n",
      "Global_step=128000: valid cost=0.00394663; p=1.39706, r=0.568919, f1=0.404284, time=4608.06s\n",
      "('The save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-6')\n",
      "EPOCH 7, lr= 0.000213363\n",
      "Global_step=136000: valid cost=0.00394409; p=1.40017, r=0.57006, f1=0.405121, time=4664.71s\n",
      "('The save path is ', '../ckpt/c2-1-bigru-256/model.ckpt-7')\n",
      "Global_step=144000: valid cost=0.00396217; p=1.3998, r=0.569825, f1=0.404971, time=4602.47s\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-5-afff89fcf6d4>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m     34\u001b[0m         feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, X3_inputs:X3_batch, X4_inputs:X4_batch, y_inputs:y_batch, \n\u001b[1;32m     35\u001b[0m                      batch_size:_batch_size, lr:_lr, keep_prob:0.5, tst:False, n_updates:global_step}\n\u001b[0;32m---> 36\u001b[0;31m         \u001b[0msummary\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_cost\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msess\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrun\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfetches\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfeed_dict\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# the cost is the mean cost of one batch\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     37\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mglobal_step\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;36m500\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     38\u001b[0m             \u001b[0mtrain_writer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0madd_summary\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msummary\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mglobal_step\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/peng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36mrun\u001b[0;34m(self, fetches, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m    787\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    788\u001b[0m       result = self._run(None, fetches, feed_dict, options_ptr,\n\u001b[0;32m--> 789\u001b[0;31m                          run_metadata_ptr)\n\u001b[0m\u001b[1;32m    790\u001b[0m       \u001b[0;32mif\u001b[0m \u001b[0mrun_metadata\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    791\u001b[0m         \u001b[0mproto_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mtf_session\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mTF_GetBuffer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrun_metadata_ptr\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/peng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_run\u001b[0;34m(self, handle, fetches, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m    995\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mfinal_fetches\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0mfinal_targets\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    996\u001b[0m       results = self._do_run(handle, final_targets, final_fetches,\n\u001b[0;32m--> 997\u001b[0;31m                              feed_dict_string, options, run_metadata)\n\u001b[0m\u001b[1;32m    998\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    999\u001b[0m       \u001b[0mresults\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/peng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_do_run\u001b[0;34m(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)\u001b[0m\n\u001b[1;32m   1130\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mhandle\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mNone\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1131\u001b[0m       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,\n\u001b[0;32m-> 1132\u001b[0;31m                            target_list, options, run_metadata)\n\u001b[0m\u001b[1;32m   1133\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1134\u001b[0m       return self._do_call(_prun_fn, self._session, handle, feed_dict,\n",
      "\u001b[0;32m/home/peng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_do_call\u001b[0;34m(self, fn, *args)\u001b[0m\n\u001b[1;32m   1137\u001b[0m   \u001b[0;32mdef\u001b[0m \u001b[0m_do_call\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1138\u001b[0m     \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1139\u001b[0;31m       \u001b[0;32mreturn\u001b[0m \u001b[0mfn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m   1140\u001b[0m     \u001b[0;32mexcept\u001b[0m \u001b[0merrors\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mOpError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1141\u001b[0m       \u001b[0mmessage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcompat\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mas_text\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0me\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmessage\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m/home/peng/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc\u001b[0m in \u001b[0;36m_run_fn\u001b[0;34m(session, feed_dict, fetch_list, target_list, options, run_metadata)\u001b[0m\n\u001b[1;32m   1119\u001b[0m         return tf_session.TF_Run(session, options,\n\u001b[1;32m   1120\u001b[0m                                  \u001b[0mfeed_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfetch_list\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtarget_list\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m-> 1121\u001b[0;31m                                  status, run_metadata)\n\u001b[0m\u001b[1;32m   1122\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m   1123\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0m_prun_fn\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msession\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mhandle\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfeed_dict\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mfetch_list\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "train_op = train_op2\n",
    "time0 = time.time()\n",
    "\n",
    "for epoch in xrange(max_max_epoch):\n",
    "    batch_indexs = np.random.permutation(n_tr_batches)  # shuffle the training data\n",
    "    if epoch == max_epoch:\n",
    "        train_op = train_op1\n",
    "        if model_num == 0:\n",
    "            model_num += 1\n",
    "            save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "            print('the save path is ', save_path)\n",
    "        print('Begin updating embedding.')\n",
    "    print 'EPOCH %d, lr= %g' % (epoch+1, _lr)    \n",
    "    for batch in xrange(n_tr_batches): \n",
    "        global_step += 1\n",
    "        if (global_step+1) % decay_step == 0:\n",
    "            _lr = _lr * decay\n",
    "        if (global_step+1) % valid_step == 0:    # 进行 valid 计算\n",
    "            valid_cost, precision, recall, f1 = valid_epoch()\n",
    "            print('Global_step=%d: valid cost=%g; p=%g, r=%g, f1=%g, time=%gs' % (\n",
    "                    global_step+1, valid_cost, precision, recall, f1, time.time()-time0))\n",
    "            time0 = time.time()\n",
    "            if (f1 > last_f1):\n",
    "                last_f1 = f1\n",
    "                model_num += 1\n",
    "                save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "                print('The save path is ', save_path)\n",
    "                \n",
    "        batch_id = batch_indexs[batch]\n",
    "        [X1_batch, X2_batch, X3_batch, X4_batch, y_batch] = get_batch(batch_id, mode='train')\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        fetches = [merged, cost, train_op, update_op]\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, X3_inputs:X3_batch, X4_inputs:X4_batch, y_inputs:y_batch, \n",
    "                     batch_size:_batch_size, lr:_lr, keep_prob:0.5, tst:False, n_updates:global_step}\n",
    "        summary, _cost, _, _ = sess.run(fetches, feed_dict) # the cost is the mean cost of one batch\n",
    "        if global_step % 500:\n",
    "            train_writer.add_summary(summary, global_step)\n",
    "            batch_id = np.random.randint(0, n_va_batches)   # 随机选一个验证batch\n",
    "            [X1_batch, X2_batch, X3_batch, X4_batch, y_batch] = get_batch(batch_id, mode='valid')\n",
    "            y_batch = to_categorical(y_batch)\n",
    "            _batch_size = len(y_batch)\n",
    "            feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, X3_inputs:X3_batch, X4_inputs:X4_batch, y_inputs:y_batch, \n",
    "                         batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "            fetches = [merged, cost]\n",
    "            summary, _cost = sess.run(fetches, feed_dict)\n",
    "            test_writer.add_summary(summary, global_step)\n",
    "\n",
    "valid_cost, precision, recall, f1 = valid_epoch()  # # 每个 epoch 进行一次验证 valid\n",
    "print('Global_step=%d;  valid cost=%g; p=%g, r=%g, f1=%g; speed=%g s/epoch' % (\n",
    "    global_step+1, valid_cost, precision, recall, f1, time.time()-time0) )\n",
    "if (f1 > last_f1):\n",
    "    model_num += 1\n",
    "    save_path = saver.save(sess, model_path, global_step=model_num)\n",
    "    print('the save path is ', save_path) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Bi-LSTM 模型<br/>\n",
    "**batch_size=256，迭代12个epoch，基本收敛。结果： 验证集 f1=0.38618； 提交结果 0.3873186**\n",
    "- Bi-GRU 模型<br/>\n",
    "**batch_size=256，迭代15个epoch。大概在 13 个 epoch 就收敛了。结果： 验证集 f1=0.390534； 提交结果 0.39198**\n",
    "- attention-Bi-GRU 模型<br/>\n",
    "**batch_size=256，迭代18个epoch。在16个epoch收敛。结果：验证集 f1=f1=0.391734 ；提交结果 0.39310**\n",
    "\n",
    "\n",
    "- textcnn-256 lr=1e-3, decay=0.65, dropout=0.5, 迭代6次基本收敛， f1=0.388\n",
    "- textcnn-256-bn lr=1.5E-3，decay=0.65, dropout=0.5, 6次基本收敛，8次好一点， f1=0.389\n",
    "- textcnn-fc-drop 迭代 4.5 个epoch 收敛。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 本地测试\n",
    "使用 seed13 的前 10万条数据."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from ../ckpt/c2-1-bigru-256/model.ckpt-7\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  0%|          | 1/782 [00:00<02:14,  5.80it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Finished loading model.\n",
      "local predicting ...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 782/782 [02:13<00:00,  6.27it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "local valid p=1.40017, r=0.57006, f1=0.405121; speed=134.006 s/epoch\n",
      "Writed the scores into ../local_scores/c2-1-bigru-256.npy, time 138.159 s\n"
     ]
    }
   ],
   "source": [
    "# 导入保存好的模型\n",
    "saver = tf.train.Saver()\n",
    "best_model_path = model_path + '-' + str(7)  # 导入最优模型\n",
    "saver.restore(sess, best_model_path)\n",
    "print('Finished loading model.')\n",
    "\n",
    "from tqdm import tqdm\n",
    "local_scores_path = '../local_scores/' + model_name + '.npy'\n",
    "\n",
    "# 导入测试数据\n",
    "def local_predict(scores_path=local_scores_path):\n",
    "    \"\"\"预测  valid 结果，并保存预测概率 到  scores.csv 文件中。\"\"\"\n",
    "    print('local predicting ...')\n",
    "    time0 = time.time()\n",
    "    fetches = [y_pred]   \n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    predict_scores = list()\n",
    "    marked_labels_list = list()   # 真实标签\n",
    "    for i in tqdm(xrange(n_va_batches)):\n",
    "        [X1_batch, X2_batch, X3_batch, X4_batch, y_batch] = get_batch(i, mode='valid')\n",
    "        marked_labels_list.extend(y_batch)\n",
    "        y_batch = to_categorical(y_batch)\n",
    "        _batch_size = len(y_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, X3_inputs:X3_batch, X4_inputs:X4_batch,\n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "        predict_labels = sess.run(fetches, feed_dict)[0]\n",
    "        predict_scores.append(predict_labels)\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_scores = np.asarray(predict_scores)\n",
    "    predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "    precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "    print('local valid p=%g, r=%g, f1=%g; speed=%g s/epoch' % ( precision, recall, f1, time.time()-time0) )\n",
    "    np.save(local_scores_path, predict_scores)\n",
    "    print('Writed the scores into %s, time %g s' % (local_scores_path, time.time()-time0))\n",
    "    \n",
    "local_predict()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 对测试数据进行预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_test_batch(batch_id):\n",
    "    \"\"\"get a batch from data_path.\n",
    "    model: 'train', 'valid' 三种方式。\n",
    "    \"\"\"\n",
    "    wd_path = '/home/peng/huangyongye/wd-data/seg_test/'\n",
    "    ch_path = '/home/peng/huangyongye/ch-data/seg_test/'\n",
    "    wd_X_batch = np.load(wd_path + str(batch_id) + '.npy')\n",
    "    X1_batch = wd_X_batch[:, :n_step1]\n",
    "    X2_batch = wd_X_batch[:, n_step1:]\n",
    "    ch_X_batch = np.load(ch_path + str(batch_id) + '.npy')\n",
    "    X3_batch = ch_X_batch[:, :n_step3]\n",
    "    X4_batch = ch_X_batch[:, n_step3:]\n",
    "    return [X1_batch, X2_batch, X3_batch, X4_batch]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "topics_ids = np.load('../data/topics_ids.npz')\n",
    "sr_id2topic = pd.Series(topics_ids['topics'], index=topics_ids['ids'])\n",
    "sr_topic2id = pd.Series(topics_ids['ids'], index=topics_ids['topics'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# 导入保存好的模型\n",
    "# saver = tf.train.Saver()\n",
    "# best_model_path = model_path + '-' + str(8)  # 导入最优模型\n",
    "# saver.restore(sess, best_model_path)\n",
    "# print('Finished loading model.')\n",
    "\n",
    "# 导入测试数据\n",
    "def predict():\n",
    "    \"\"\"预测测试集结果，并保存到  result.csv 文件中。\"\"\"\n",
    "    n_te_batches = len(os.listdir('/home/peng/huangyongye/wd-data/seg_test/'))\n",
    "    fetches = [y_pred]   \n",
    "    predict_labels_list = list()  # 所有的预测结果\n",
    "    predict_scores = list()\n",
    "    for i in xrange(n_te_batches):\n",
    "        [X1_batch, X2_batch, X3_batch, X4_batch] = get_test_batch(i)\n",
    "        _batch_size = len(X1_batch)\n",
    "        feed_dict = {X1_inputs:X1_batch, X2_inputs:X2_batch, X3_inputs:X3_batch, X4_inputs:X4_batch, \n",
    "                     batch_size:_batch_size, keep_prob:1.0, tst:True, n_updates:global_step}\n",
    "        predict_labels = sess.run(fetches, feed_dict)[0]\n",
    "        predict_scores.append(predict_labels)\n",
    "        predict_labels = map(lambda label: label.argsort()[-1:-6:-1], predict_labels) # 取最大的5个下标\n",
    "        predict_labels_list.extend(predict_labels)\n",
    "    predict_scores = np.asarray(predict_scores)\n",
    "    return predict_labels_list, np.vstack(predict_scores)\n",
    "\n",
    "def write_result(predict_labels_list, result_path):\n",
    "    \"\"\"把结果写到 result.csv 中\"\"\"\n",
    "    eval_question = np.load('../data/eval_question.npy')\n",
    "    pred_labels = np.asarray(predict_labels_list).reshape([-1])\n",
    "    pred_topics = sr_id2topic[pred_labels].values.reshape([-1, 5])   # 转为 topic\n",
    "    df_result = pd.DataFrame({'question':eval_question, 'tid0': pred_topics[:,0], 'tid1':pred_topics[:, 1],\n",
    "                         'tid2': pred_topics[:,2], 'tid3':pred_topics[:,3],'tid4': pred_topics[:,4]})\n",
    "    df_result.to_csv(result_path, index=False, header=False)\n",
    "    print('Finished writing the result')\n",
    "    return df_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Finished writing the result\n",
      "('len(df_result)=', 217360)\n",
      "Saving the predict_scores into ../scores/c2-1-bigru-256.npy\n",
      "('predict_scores.shape=', (217360, 1999))\n",
      "Finished saving the result!\n"
     ]
    }
   ],
   "source": [
    "# %time predict_labels_list,predict_scores = predict()\n",
    "df_result = write_result(predict_labels_list, result_path=result_path) \n",
    "print('len(df_result)=',len(df_result))  # 结果应该为 217360\n",
    "print('Saving the predict_scores into %s' % scores_path)\n",
    "print('predict_scores.shape=',predict_scores.shape)\n",
    "np.save(scores_path, predict_scores)\n",
    "print('Finished saving the result!')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>tid0</th>\n",
       "      <th>tid1</th>\n",
       "      <th>tid2</th>\n",
       "      <th>tid3</th>\n",
       "      <th>tid4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6215603645409872328</td>\n",
       "      <td>4610596224687453206</td>\n",
       "      <td>-7506384235581390893</td>\n",
       "      <td>-6839713564940654454</td>\n",
       "      <td>-6306904715218704629</td>\n",
       "      <td>2919247920214845195</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6649324930261961840</td>\n",
       "      <td>-240041917918953337</td>\n",
       "      <td>3418451812342379591</td>\n",
       "      <td>2858911571784840089</td>\n",
       "      <td>-7483543763655495143</td>\n",
       "      <td>9149698301250936831</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-4251899610700378615</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-7358589937244777363</td>\n",
       "      <td>-7270992690764838239</td>\n",
       "      <td>2816249700493135244</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6213817087034420233</td>\n",
       "      <td>5804619920623030604</td>\n",
       "      <td>-8655945395761165989</td>\n",
       "      <td>-4966205278807386328</td>\n",
       "      <td>7476760589625268543</td>\n",
       "      <td>244937959911721367</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-8930652370334418373</td>\n",
       "      <td>3972493657017129406</td>\n",
       "      <td>-8963554618409314978</td>\n",
       "      <td>-1115593437686158905</td>\n",
       "      <td>-985918886318729368</td>\n",
       "      <td>1870872991887862017</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>-2893445476547593888</td>\n",
       "      <td>-6206436693745657677</td>\n",
       "      <td>2131451573312950491</td>\n",
       "      <td>-2696736445927423374</td>\n",
       "      <td>-8274522839089381384</td>\n",
       "      <td>-3900318848301728120</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2614833994648160978</td>\n",
       "      <td>4482402820945758152</td>\n",
       "      <td>-3856154743789177934</td>\n",
       "      <td>-6748914495015758455</td>\n",
       "      <td>-3904210248050890128</td>\n",
       "      <td>1553849747662134917</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>1572988006266661060</td>\n",
       "      <td>-839691564858654120</td>\n",
       "      <td>3738968195649774859</td>\n",
       "      <td>-8932546057542867495</td>\n",
       "      <td>-2627298052801704596</td>\n",
       "      <td>1160326435131345730</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>-3736249911643942320</td>\n",
       "      <td>-7653703019053330516</td>\n",
       "      <td>8690965822342756180</td>\n",
       "      <td>738845194850773558</td>\n",
       "      <td>1127459907694805235</td>\n",
       "      <td>5502528845814007324</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>-976507019126932319</td>\n",
       "      <td>3195914392210930723</td>\n",
       "      <td>3804601920633030746</td>\n",
       "      <td>6940355838132160535</td>\n",
       "      <td>701949295768128821</td>\n",
       "      <td>6718676536613592056</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>5515590371171945660</td>\n",
       "      <td>-1689319711084901730</td>\n",
       "      <td>4195795391451929480</td>\n",
       "      <td>4351331710881888756</td>\n",
       "      <td>3804601920633030746</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>6888753259805649782</td>\n",
       "      <td>4931893522763265934</td>\n",
       "      <td>7283655748413496857</td>\n",
       "      <td>-6254806834008898035</td>\n",
       "      <td>-9176307901497282391</td>\n",
       "      <td>6940355838132160535</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>7873230180977758006</td>\n",
       "      <td>4730384719025183341</td>\n",
       "      <td>-6440461292041887516</td>\n",
       "      <td>-4496395654369317320</td>\n",
       "      <td>-5932391056759866388</td>\n",
       "      <td>-3026760652624195547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1805154204046808321</td>\n",
       "      <td>3738968195649774859</td>\n",
       "      <td>-839691564858654120</td>\n",
       "      <td>1160326435131345730</td>\n",
       "      <td>-2627298052801704596</td>\n",
       "      <td>-8932546057542867495</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>5466502219528315935</td>\n",
       "      <td>616649108700697054</td>\n",
       "      <td>-3333307402327293632</td>\n",
       "      <td>2787171473654490487</td>\n",
       "      <td>5370870069386720811</td>\n",
       "      <td>2190609939333204140</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                question                  tid0                  tid1  \\\n",
       "0    6215603645409872328   4610596224687453206  -7506384235581390893   \n",
       "1    6649324930261961840   -240041917918953337   3418451812342379591   \n",
       "2   -4251899610700378615   2919247920214845195  -7358589937244777363   \n",
       "3    6213817087034420233   5804619920623030604  -8655945395761165989   \n",
       "4   -8930652370334418373   3972493657017129406  -8963554618409314978   \n",
       "5   -2893445476547593888  -6206436693745657677   2131451573312950491   \n",
       "6    2614833994648160978   4482402820945758152  -3856154743789177934   \n",
       "7    1572988006266661060   -839691564858654120   3738968195649774859   \n",
       "8   -3736249911643942320  -7653703019053330516   8690965822342756180   \n",
       "9    -976507019126932319   3195914392210930723   3804601920633030746   \n",
       "10   5515590371171945660  -1689319711084901730   4195795391451929480   \n",
       "11   6888753259805649782   4931893522763265934   7283655748413496857   \n",
       "12   7873230180977758006   4730384719025183341  -6440461292041887516   \n",
       "13   1805154204046808321   3738968195649774859   -839691564858654120   \n",
       "14   5466502219528315935    616649108700697054  -3333307402327293632   \n",
       "\n",
       "                    tid2                  tid3                  tid4  \n",
       "0   -6839713564940654454  -6306904715218704629   2919247920214845195  \n",
       "1    2858911571784840089  -7483543763655495143   9149698301250936831  \n",
       "2   -7270992690764838239   2816249700493135244  -5265476641576484497  \n",
       "3   -4966205278807386328   7476760589625268543    244937959911721367  \n",
       "4   -1115593437686158905   -985918886318729368   1870872991887862017  \n",
       "5   -2696736445927423374  -8274522839089381384  -3900318848301728120  \n",
       "6   -6748914495015758455  -3904210248050890128   1553849747662134917  \n",
       "7   -8932546057542867495  -2627298052801704596   1160326435131345730  \n",
       "8     738845194850773558   1127459907694805235   5502528845814007324  \n",
       "9    6940355838132160535    701949295768128821   6718676536613592056  \n",
       "10   4351331710881888756   3804601920633030746  -5265476641576484497  \n",
       "11  -6254806834008898035  -9176307901497282391   6940355838132160535  \n",
       "12  -4496395654369317320  -5932391056759866388  -3026760652624195547  \n",
       "13   1160326435131345730  -2627298052801704596  -8932546057542867495  \n",
       "14   2787171473654490487   5370870069386720811   2190609939333204140  "
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df_result.head(15)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>question</th>\n",
       "      <th>tid0</th>\n",
       "      <th>tid1</th>\n",
       "      <th>tid2</th>\n",
       "      <th>tid3</th>\n",
       "      <th>tid4</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>6215603645409872328</td>\n",
       "      <td>4610596224687453206</td>\n",
       "      <td>-6839713564940654454</td>\n",
       "      <td>-6306904715218704629</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-8091907016971478715</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>6649324930261961840</td>\n",
       "      <td>3418451812342379591</td>\n",
       "      <td>2858911571784840089</td>\n",
       "      <td>2382911985227044227</td>\n",
       "      <td>-240041917918953337</td>\n",
       "      <td>3383016985780045156</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>-4251899610700378615</td>\n",
       "      <td>2919247920214845195</td>\n",
       "      <td>-7358589937244777363</td>\n",
       "      <td>2816249700493135244</td>\n",
       "      <td>-5265476641576484497</td>\n",
       "      <td>-3315241959305847628</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>6213817087034420233</td>\n",
       "      <td>-8655945395761165989</td>\n",
       "      <td>5804619920623030604</td>\n",
       "      <td>-4966205278807386328</td>\n",
       "      <td>7476760589625268543</td>\n",
       "      <td>-2523521411748733187</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>-8930652370334418373</td>\n",
       "      <td>3972493657017129406</td>\n",
       "      <td>-8963554618409314978</td>\n",
       "      <td>-1115593437686158905</td>\n",
       "      <td>1870872991887862017</td>\n",
       "      <td>6018641953300645757</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "               question                  tid0                  tid1  \\\n",
       "0   6215603645409872328   4610596224687453206  -6839713564940654454   \n",
       "1   6649324930261961840   3418451812342379591   2858911571784840089   \n",
       "2  -4251899610700378615   2919247920214845195  -7358589937244777363   \n",
       "3   6213817087034420233  -8655945395761165989   5804619920623030604   \n",
       "4  -8930652370334418373   3972493657017129406  -8963554618409314978   \n",
       "\n",
       "                   tid2                  tid3                  tid4  \n",
       "0  -6306904715218704629   2919247920214845195  -8091907016971478715  \n",
       "1   2382911985227044227   -240041917918953337   3383016985780045156  \n",
       "2   2816249700493135244  -5265476641576484497  -3315241959305847628  \n",
       "3  -4966205278807386328   7476760589625268543  -2523521411748733187  \n",
       "4  -1115593437686158905   1870872991887862017   6018641953300645757  "
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 参考结果\n",
    "df_result.head(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在全部预测正确的情况下，理论值为：f1=0.713933\n",
    "precision=2.50273, recall=0.998873, f1=0.713933"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "在全部预测正确的情况下，理论值为：\n",
      "precision=2.50273, recall=0.998873, f1=0.713933\n"
     ]
    }
   ],
   "source": [
    "# 假设全部正确，f1 值最高能到多少\n",
    "def padding_label(labels):\n",
    "    \"\"\"把所有的label补齐到长度为 5\"\"\"\n",
    "    label_len = len(labels)\n",
    "    if label_len >= 5:\n",
    "        return labels[:5]\n",
    "    return np.hstack([labels, np.zeros(5-label_len, dtype=int) - 1])\n",
    "    \n",
    "\n",
    "marked_labels_list = data_valid.y.tolist() # 所有的标注结果\n",
    "predict_labels_list = map(padding_label, marked_labels_list)\n",
    "predict_label_and_marked_label_list = zip(predict_labels_list, marked_labels_list)\n",
    "precision, recall, f1 = score_eval(predict_label_and_marked_label_list)\n",
    "print '在全部预测正确的情况下，理论值为：'\n",
    "print 'precision=%g, recall=%g, f1=%g' % (precision, recall, f1)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
